package com.starblink.brand.search.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.blankj.utilcode.util.GsonUtils
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.config.StorageKeys
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.ActivityStackManage
import com.starblink.brand.BrandHelper
import com.starblink.brand.search.bean.RvNoDataEntry
import com.starblink.brand.search.bean.RvProductWapper
import com.starblink.brand.search.bean.RvRecommendTitleEntry
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.rocketreserver.FetchTopBrandProductListQuery
import com.starblink.rocketreserver.SearchTopBrandProductQuery
import com.starblink.rocketreserver.type.TopBrandProductListReq
import com.starblink.rocketreserver.type.TopBrandSearchProductReq
import kotlinx.coroutines.launch
import java.util.LinkedList

class BrandSearchVM : BaseViewModel() {
    // ===页面传参
    var brandId = ""
    var brandName = ""
    var isDiscountBrand = false //是否是折扣品牌
    // ===页面传参

    var searchKeyword = "" //搜索关键字

    // 排序方式： 0-默认排序 2-价格从高到低 3-价格从低到高 4-折扣从高到低 5-折扣从低到高
    var sortType: SortTypeEnum = SortTypeEnum.DEFAULT

    var curPageNo = 0 // 当前列表页数（搜索结果列表和推荐商品列表共用，这两个列表互斥）
    var searchResultEmpty = false //搜索结果是否为空

    var searchProducts = arrayListOf<Any>() //保存全部列表数据
    var searchResultLD: MutableLiveData<ResultData> = MutableLiveData() // 保存搜索结果

    class ResultData(
        val searchProducts: ArrayList<Any>, // 搜索商品列表
        var isRefresh: Boolean = false, // 是否是首页刷新
        var isShowInitStateSortView: Boolean = false, // 是否显示初始状态排序视图
    ) {}

    /**
     * 搜索店铺商品
     * @param refresh true表示获取首页搜索结果；false表示获取更多搜索结果
     * @param isShowInitStateSortView 仅当搜索新文本，并成功返回搜索结果时，显示初始状态排序视图
     */
    fun searchProducts(refresh: Boolean = true, isShowInitStateSortView: Boolean = false) {
        if (refresh) {
            // 刷新页面，显示页面Loading，禁止用户操作
            LoadingDialogManager.get()
                .showLoading(ActivityStackManage.currentActivity())
        }
        viewModelScope.launch {
            val requestPageNo = if (refresh) 1 else curPageNo + 1
            SkGqlClient.skQuery(
                SearchTopBrandProductQuery(
                    TopBrandSearchProductReq(
                        pageNo = requestPageNo,
                        pageSize = 20,
                        brandName = brandName,
                        isSale = false,
                        sortType = sortType.code,
                        searchWords = searchKeyword,
                    )
                )
            )?.data?.searchTopBrandProduct?.let { productLists ->
                val products = productLists.filter { it?.productF != null }
                    .map { RvProductWapper(it!!.productF, BrandHelper.showSimpleViewInBrandSearch) }
                if (products.isEmpty()) {
                    // 搜索商品列表为空
                    if (refresh) {
                        // 获取搜索结果首页，商品列表为空
                        // 此时显示空视图+推荐商品列表
                        searchResultEmpty = true
                        loadRecommendProducts(true)
                    } else {
                        // 获取更多搜索结果为空，禁止加载更多
                        loadNoData()
                    }
                } else {
                    // 搜索商品列表不为空，显示首页或更多搜索商品列表数据
                    if (refresh) {
                        searchResultEmpty = false // 必须重置状态（本次搜索前，可能显示的是空视图）
                        searchProducts.clear()
                    }
                    curPageNo = requestPageNo
                    searchProducts.addAll(products)
                    searchResultLD.postValue(
                        ResultData(
                            searchProducts = searchProducts,
                            isRefresh = refresh,
                            isShowInitStateSortView = isShowInitStateSortView,
                        )
                    )
                }
            } ?: let {
                // 获取搜索结果失败，显示错误视图
                loadError(null)
            }
        }
    }

    //获取推荐商品
    fun loadRecommendProducts(refresh: Boolean) {
        viewModelScope.launch {
            val requestPageNo = if (refresh) 1 else curPageNo + 1
            SkGqlClient.skQuery(
                FetchTopBrandProductListQuery(
                    TopBrandProductListReq(
                        pageNo = requestPageNo,
                        pageSize = 20,
                        brandId = brandId,
                        brandName = brandName,
                        isSale = false,
                        sortType = SortTypeEnum.DEFAULT.code,
                        foregroundCategoryId = Optional.Absent, // ALL
                    )
                )
            )?.data?.fetchTopBrandProductList?.let { productLists ->
                val products = productLists.filter { it?.productF != null }
                    .map { RvProductWapper(it!!.productF, BrandHelper.showSimpleViewInBrandSearch) }
                if (products.isEmpty()) {
                    // 推荐商品列表为空
                    if (refresh) {
                        // 获取首页推荐商品列表为空
                        // 此时显示空视图，禁止加载更多
                        searchProducts.clear()
                        searchProducts.add(RvNoDataEntry())
                        searchResultLD.postValue(
                            ResultData(
                                searchProducts = searchProducts,
                                isRefresh = refresh,
                            )
                        )
                    } else {
                        // 获取更多推荐商品为空，禁止加载更多
                    }
                    loadNoData()
                } else {
                    // 推荐商品列表不为空
                    if (refresh) {
                        searchProducts.clear()
                        searchProducts.add(RvNoDataEntry())
                        searchProducts.add(RvRecommendTitleEntry())
                    }
                    curPageNo = requestPageNo
                    searchProducts.addAll(products)
                    searchResultLD.postValue(
                        ResultData(
                            searchProducts = searchProducts,
                            isRefresh = refresh,
                        )
                    )
                }
            } ?: let {
                // 获取推荐商品列表失败
                if (refresh) {
                    // 获取首页推荐商品列表失败
                    // 此时显示空视图，禁止加载更多
                    searchProducts.clear()
                    searchProducts.add(RvNoDataEntry())
                    searchResultLD.postValue(
                        ResultData(
                            searchProducts = searchProducts,
                            isRefresh = refresh,
                        )
                    )
                    loadNoData()
                } else {
                    // 获取更多推荐商品失败，结束加载更多
                    loadError(null)
                }
            }
        }
    }

    // <editor-fold desc="历史搜索词">
    val historySearchWords = LinkedList<String>() // 历史搜索词
    val historySearchWordsLD = MutableLiveData<Boolean>() // 是否有历史搜索词

    /**
     * 加载店铺搜索页面历史搜索词（本地）
     */
    fun loadHistorySearchWords() {
        viewModelScope.launch {
            GsonUtils.fromJson(
                SkStorage.getString(
                    "${StorageKeys.SEARCH_BRAND_HISTORY}",
                    ""
                ), historySearchWords.javaClass
            )?.let {
                historySearchWords.clear()
                historySearchWords.addAll(it)
                historySearchWordsLD.postValue(historySearchWords.isNotEmpty())
            } ?: let {
                historySearchWordsLD.postValue(false)
            }
        }
    }

    /**
     * 将搜索词保存至历史搜索词列表中（本地）
     */
    fun saveToHistorySearchWords(word: String) {
        historySearchWords.remove(word)
        historySearchWords.add(0, word)
        while (historySearchWords.size >= 20) {
            historySearchWords.removeLast()
        }
        SkStorage.put(
            "${StorageKeys.SEARCH_BRAND_HISTORY}",
            GsonUtils.toJson(historySearchWords)
        )
    }

    fun clearHistorySearchWords() {
        historySearchWords.clear()
        historySearchWordsLD.postValue(false)
        SkStorage.remove("${StorageKeys.SEARCH_BRAND_HISTORY}")
    }
    // </editor-fold>
}